package com.android.baselibrary.titlebar

import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import com.android.baselibrary.R
import com.android.baselibrary.databinding.ViewTitleBarBinding

class TitleBar @JvmOverloads constructor(
    context: Context, attributeSet: AttributeSet? = null, defaultStyle: Int = 0
) : RelativeLayout(context, attributeSet, defaultStyle) {
    private var binding: ViewTitleBarBinding = DataBindingUtil.inflate(
        LayoutInflater.from(context),
        R.layout.view_title_bar, this, true
    )
    private var mColor: Int = 0
    private var mTextColor: Int = 0
    private var mTitle: String = ""

    init {
        val array = context.obtainStyledAttributes(attributeSet, R.styleable.TitleBar)
        mColor = array.getColor(R.styleable.TitleBar_title_bg, Color.BLUE)
        mTextColor = array.getColor(R.styleable.TitleBar_title_text_color, Color.WHITE)
        mTitle = array.getString(R.styleable.TitleBar_title).toString()

        array.recycle()

        binding.rlBg.setBackgroundColor(mColor)
        binding.tvTitlebarTitle.text = mTitle
        binding.tvTitlebarTitle.setTextColor(mTextColor)
    }

    fun setTitle(titleName: String) {
        if (!TextUtils.isEmpty(titleName)) {
            binding.tvTitlebarTitle.text = titleName
        }
    }

    fun setLeftListener(onClickListener: OnClickListener) {
        binding.ivTitlebarLeft.setOnClickListener(onClickListener)
    }

    fun setRightListener(onClickListener: OnClickListener) {
        binding.ivTitlebarRight.setOnClickListener(onClickListener)
    }
}